# -*- coding: utf-8 -*-
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.context_processors import csrf
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.http import HttpResponseRedirect, Http404
from django.shortcuts import render_to_response
from django.template import Context, RequestContext
from sprt import createExtInfo, get_200_response, get_date_range
from sprt.accounts.forms import RegisterUserForm
from sprt.accounts.models import UserDetail
from sprt.admin.forms import CreateDeptForm, HolidayForm, WorkdayForm
from sprt.admin.models import Dept, Holiday, Workday
from sprt.schedule.models import ScheduleType




# Create your views here.
DAILY = 1
WEEKLY = 2
MONTHLY= 4
    
@login_required
def create_dept(request):
    if not request.user.is_superuser:
        raise Http404
    
    if request.GET.has_key("parent"):
        try:
            d = Dept.objects.get(pk=int(request.GET["parent"]))
        except Dept.DoesNotExist:
            raise Http404
    
    if request.method == 'POST':
        form = CreateDeptForm(request.POST)
        if form.is_valid():
            dept=Dept(name=form.cleaned_data["name"],superior_dept_id=form.cleaned_data["superior_dept_id"].id,principal_auth_user_id=form.cleaned_data["principal_auth_user_id"].id)
            dept.save()
#            return get_200_response("dept_detail_page","closeCurrent",("/admin/dept/%d" % dept.id))
            return HttpResponseRedirect("/admin/dept/%d" % dept.id);
    else:
        form = CreateDeptForm()
    c = RequestContext(request,{"form":form})
    c.update(csrf(request))
    if request.GET.has_key("parent"):
        c["dept"] = d
        form.initial = {"superior_dept_id":d.id}
    createExtInfo(request,c)
    return render_to_response("admin/create_dept.html",c)

#@login_required    
#def create_schedule_type(request):
#    if not request.user.is_superuser:
#        raise Http404
#    
#    if request.method == 'POST':
#        form=CreateScheduleTypeForm(request.POST)
#        if form.is_valid():
#            scheduleType=ScheduleType(name=form.cleaned_data['name'])
#            scheduleType.save()
#        else:
#            errList=form.errors
#    else:
#        form=CreateScheduleTypeForm()
#    c = RequestContext(request,{"form":form})
#    c.update(csrf(request))
#    createExtInfo(request,c)
#    return render_to_response("admin/create_schedule_type.html",c)

@login_required
def edit_todolist(request, user_id):
    if not request.user.is_superuser:
        raise Http404
    
    if request.method == 'POST':
        p = request.POST.copy()
        user = User.objects.get(pk=p.get("user_id"))
        user_detail = user.get_profile()
        v=0
        if p.get("daily","") == "1":
            v=DAILY
        if p.get("weekly","") == "2":
            v+=WEEKLY
        if p.get("monthly","") == "4":
            v+=MONTHLY
        if v != user_detail.schedule_list:
            user_detail.schedule_list=v
            user_detail.save()
        c = Context(p)
    else:
        user = User.objects.get(pk=user_id)
        user_detail = user.get_profile()
        c = Context({"daily":DAILY&user_detail.schedule_list,"weekly":WEEKLY&user_detail.schedule_list,"monthly":MONTHLY&user_detail.schedule_list,"user_id":user.id})
    c.update(csrf(request))
    createExtInfo(request,c)
    return render_to_response("admin/edit_todolist.html",c)

@login_required
def register(request):
    if not request.user.is_superuser:
        raise Http404
    
    if request.method == 'POST':
#        form = UserCreationForm(request.POST)
        form=RegisterUserForm(request.POST)
        if form.is_valid():
            form.save()
            print "form.instance.id", form.instance.id
            return HttpResponseRedirect("/admin/user/%d" % form.instance.id)#get_200_response("user_detail_page","closeCurrent","/admin/user/2")
        else:
            errs=form.errors
    else:
        form = RegisterUserForm() #UserCreationForm()
    c = RequestContext(request,{"form":form})
    c.update(csrf(request))
    createExtInfo(request,c)
    return render_to_response("accounts/register.html", c)

@login_required
def register_dept_user(request, dept_id):
    if not request.user.is_superuser:
        raise Http404
    try:
        dept = Dept.objects.get(pk=dept_id)
    except Dept.DoesNotExist:
        raise Http404
    
    if request.method == 'POST':
#        form = UserCreationForm(request.POST)
        form=RegisterUserForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect("/admin/user/%d" % form.instance.id)
#            return get_200_response("user_detail_page","closeCurrent",("/admin/user/%d" % form.instance.id))
        else:
            errs=form.errors
    else:
        form = RegisterUserForm(initial={"dept":dept}) #UserCreationForm()
    c = RequestContext(request,{"form":form,"dept":dept})
    c.update(csrf(request))
    createExtInfo(request,c)
    return render_to_response("accounts/register.html", c)

@login_required
def view_dept(request, id):
    if not request.user.is_superuser:
        raise Http404
    
    try:
        dept = Dept.objects.get(pk=id)
    except Dept.DoesNotExist:
        raise Http404
    
    if request.method == 'POST':
        form = CreateDeptForm(request.POST)
        if form.is_valid():
            dept.name=form.cleaned_data["name"]
            dept.superior_dept=form.cleaned_data["superior_dept_id"]
            dept.principal_auth_user=form.cleaned_data["principal_auth_user_id"]
            dept.save()
            return HttpResponseRedirect("/admin/dept/%d" % dept.id)
#            return get_200_response("dept_detail_page","closeCurrent",("/admin/dept/%d" % dept.id))
    else:
        map = {"name":dept.name,"principal_auth_user_id":dept.principal_auth_user.id}
        if dept.superior_dept != None:
            map["superior_dept_id"]=dept.superior_dept.id
        form = CreateDeptForm(initial=map)
        c = RequestContext(request,{"form":form})
        c.update(csrf(request))
        c["dept_id"]=id
        createExtInfo(request,c)
        return render_to_response("admin/create_dept.html",c)

@login_required
def view_user(request, id):
    if not request.user.is_superuser:
        raise Http404
    
    try:
        user = User.objects.get(pk=id)
        user_detail = user.get_profile()
    except User.DoesNotExist:
        raise Http404
    if request.method == "POST":
        p = request.POST.copy()
        username = p.get("username")
        pwd1 = p.get("password1")
        pwd2 = p.get("password2")
        last_name = p.get("last_name")
        email = p.get("email")
        gender = p.get("gender")
        title = p.get("title")
        birthday = p.get("birthday")
        
        if len(pwd1) > 0 and len(pwd2) > 0 and pwd1 == pwd2 :
            user.set_password(pwd1)
        user.last_name = last_name
        user.username = username
        user.email = email
        user.save()
        user_detail.gender = gender;
        user_detail.title = title;
        user.bithday = birthday
        v = 0
        if p.get("daily","") == "1":
            v=DAILY
        if p.get("weekly","") == "2":
            v+=WEEKLY
        if p.get("monthly","") == "4":
            v+=MONTHLY
        user_detail.schedule_list=v
        user_detail.save()
#        return get_200_response("detail_page","closeCurrent","/admin/user/"+str(id))
        return HttpResponseRedirect("/admin/user/%s" % id)
    else:
        c = RequestContext(request)
        c["edit_user"]=user
        c["edit_user_detail"]=user_detail
        c.update(csrf(request))
        createExtInfo(request,c)
        return render_to_response("admin/edit_user.html",c)


@login_required
def list_holiday(request):
    if not request.user.is_superuser:
        raise Http404
    pn = request.GET.get('pageNum')
    dt1,dt2 = get_date_range(request.REQUEST.get('dt1'),request.REQUEST.get('dt2'))
    c = RequestContext(request)
    dt1Str = dt1.strftime("%Y-%m-%d")
    dt2Str = dt2.strftime("%Y-%m-%d")
    paginator = Paginator(Holiday.objects.filter(start_date__gte=dt1Str,end_date__lte=dt2Str),20)
    if pn == None or len(pn) == 0:
        pn =1
    else:
        pn = int(pn)
    try:
        list = paginator.page(pn)
    except PageNotAnInteger:
        list = paginator.page(1)
    except EmptyPage:
        list = paginator.page(paginator.num_pages)
    c["list"] = list
    c["nav_url"]="%s?dt1=%s&amp;dt2=%s&amp;pageNum=%s" % (request.path,dt1Str, dt2Str,"%d")
    c["pc"] = paginator.num_pages
    c["pn"] = pn
    c["dt1"]=dt1
    c["dt2"]=dt2
    createExtInfo(request,c)
    return render_to_response("admin/list_holiday.html",c)


@login_required
def create_holiday(request):
    if not request.user.is_superuser:
        raise Http404
    
    if request.method == 'POST':
        form = HolidayForm(request.POST)
        if form.is_valid():
            form.save()
#            return get_200_response("list_holiday_page","closeCurrent","/admin/holiday/list")
            return HttpResponseRedirect("/admin/holiday/list")
    else:
        form = HolidayForm()
        c = RequestContext(request)
        c["form"] = form
        createExtInfo(request,c)
    return render_to_response("admin/create_holiday.html",c)

@login_required
def list_workday(request):
    if not request.user.is_superuser:
        raise Http404
    pn = request.GET.get('pageNum')
    dt1,dt2 = get_date_range(request.POST.get('dt1'),request.POST.get('dt2'))
    c = RequestContext(request)
    dt1Str = dt1.strftime("%Y-%m-%d")
    dt2Str = dt2.strftime("%Y-%m-%d")
    paginator = Paginator(Workday.objects.filter(at_date__gte=dt1Str ,at_date__lte=dt2Str),20)
    if pn == None or len(pn) == 0:
        pn =1
    else:
        pn = int(pn)
    try:
        list = paginator.page(pn)
    except PageNotAnInteger:
        list = paginator.page(1)
    except EmptyPage:
        list = paginator.page(paginator.num_pages)
        
    c["list"] = list
    c["nav_url"]="%s?dt1=%s&amp;dt2=%s&amp;pageNum=%s" % (request.path,dt1Str, dt2Str,"%d")
    c["pc"] = paginator.num_pages
    c["pn"] = pn
    c["dt1"]=dt1
    c["dt2"]=dt2
    createExtInfo(request,c)
    return render_to_response("admin/list_workday.html",c)

@login_required
def create_workday(request):
    if not request.user.is_superuser:
        raise Http404
    
    if request.method == 'POST':
        form = WorkdayForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect("/admin/workday/list")
#            return get_200_response("list_workday_page","closeCurrent","/admin/workday/list")
    else:
        form = WorkdayForm()
        c = RequestContext(request)
        c["form"] = form
        createExtInfo(request,c)
    return render_to_response("admin/create_workday.html",c)

@login_required
def delete_workday(request, id):
    if not request.user.is_superuser:
        raise Http404
    try:
        workday = Workday.objects.get(pk=id)
    except Workday.DoesNotExist:
        raise Http404
    
    workday.delete()
    return HttpResponseRedirect("/admin/workday/list")
#    return get_200_response("list_workday_page","closeCurrent","/admin/workday/list")


@login_required
def delete_holiday(request, id):
    if not request.user.is_superuser:
        raise Http404
    
    try:
        holiday = Holiday.objects.get(pk=id)
    except Holiday.DoesNotExist:
        raise Http404
    
    holiday.delete()
    return HttpResponseRedirect("/admin/holiday/list")
#    return get_200_response("list_holiday_page","closeCurrent","/admin/holiday/list")
